package com.bsoft.gol.hcb.dao;

import ctd.account.UserRoleToken;
import ctd.controller.exception.ControllerException;
import ctd.persistence.annotation.DAOMethod;
import ctd.persistence.annotation.DAOParam;
import ctd.persistence.exception.DAOException;
import ctd.persistence.support.hibernate.HibernateSupportDelegateDAO;
import ctd.persistence.support.hibernate.template.AbstractHibernateStatelessResultAction;
import ctd.persistence.support.hibernate.template.HibernateSessionTemplate;
import ctd.persistence.support.hibernate.template.HibernateStatelessAction;
import ctd.persistence.support.hibernate.template.HibernateStatelessResultAction;
import hcn.common.Constants;
import hcn.ods.OdsPatientcollect;
import hcn.util.RpcUserToken;
import org.hibernate.Query;
import org.hibernate.StatelessSession;

import java.util.List;


/**
 * @author chase
 * @Title: hcn
 * @Package hcn.ods.dao
 * @Description: ${患者收藏}
 * @date 2016/4/6 11:02
 */
public abstract class PatientCollectDAO extends HibernateSupportDelegateDAO<OdsPatientcollect> {
    public PatientCollectDAO() {
        this.setKeyField("id");
    }

    /**
     * savePatientCollect 保存患者收藏记录
     *
     * @param patientCollect
     * @return void
     * @throws ControllerException
     * @Description:
     * @author chase
     * @date 2016/4/6
     */


    public void savePatientCollect(final OdsPatientcollect patientCollect) throws ControllerException {
        HibernateStatelessResultAction<ControllerException> action = new AbstractHibernateStatelessResultAction<ControllerException>() {
            @Override
            public void execute(StatelessSession ss) throws Exception {
                String tenantId = UserRoleToken.getCurrentTenantId();
                OdsPatientcollect exist = getPatientCollectByObjectId(patientCollect.getUserId(), patientCollect.getObjectId(), patientCollect.getObjectType(),tenantId);
                if (exist != null) {
                    return;
                }
                if (tenantId == null || tenantId.isEmpty()) {
                    tenantId = RpcUserToken.getTenantId();
                }
                patientCollect.setTenantId(tenantId);
                ss.insert(getEntityName(), patientCollect);
            }
        };
        executeAction(action);
    }

    /**
     * savePatientCollectList 保存患者收藏记录列表
     *
     * @param patientCollects
     * @return void
     * @throws ControllerException
     * @Description:
     * @author chase
     * @date 2016/4/6
     */


    public void savePatientCollectList(final List<OdsPatientcollect> patientCollects) throws ControllerException {
        HibernateStatelessResultAction<ControllerException> action = new AbstractHibernateStatelessResultAction<ControllerException>() {
            @Override
            public void execute(StatelessSession ss) throws Exception {
                for (OdsPatientcollect patientCollect : patientCollects) {
                    String tenantId = UserRoleToken.getCurrentTenantId();
                    OdsPatientcollect exist = getPatientCollectByObjectId(patientCollect.getUserId(), patientCollect.getObjectId(), patientCollect.getObjectType(),tenantId);
                    if (exist != null) {
                        return;
                    }
                    if (tenantId == null || tenantId.isEmpty()) {
                        tenantId = RpcUserToken.getTenantId();
                    }
                    patientCollect.setTenantId(tenantId);
                    ss.insert(getEntityName(), patientCollect);
                }
            }
        };
        executeAction(action);
    }

    /**
     * removePatientCollect 删除患者收藏
     *
     * @param patientCollect
     * @return void
     * @throws ControllerException
     * @Description:
     * @author chase
     * @date 2016/4/6
     */
    public void removePatientCollect(final OdsPatientcollect patientCollect) throws ControllerException {
        HibernateStatelessResultAction<ControllerException> action = new AbstractHibernateStatelessResultAction<ControllerException>() {
            @Override
            public void execute(StatelessSession ss) throws Exception {
                String tenantId = UserRoleToken.getCurrentTenantId();
                OdsPatientcollect exist = getPatientCollectByObjectId(patientCollect.getUserId(), patientCollect.getObjectId(), patientCollect.getObjectType(),tenantId);
                if (exist != null) {
                    ss.delete(exist);
                }
            }
        };
        executeAction(action);
    }

    /**
     * getPatientCollectByObjectId 获取患者的收藏记录
     *
     * @param objectType 对象类型
     * @param objectId   对象ID,云平台对应的机构、医生、科室、疾病ID
     * @return PatientCollect
     * @Description: 通过对象类型，对象ID
     * @author chase
     * @date 2016/4/6
     */
    @DAOMethod(sql = "from OdsPatientcollect where userId=:userId and objectId=:objectId and objectType =:objectType and tenantId=:tenantId ")
    public abstract OdsPatientcollect getPatientCollectByObjectId(@DAOParam("userId") String userId, @DAOParam("objectId") String objectId, @DAOParam("objectType") String objectType,@DAOParam("tenantId") String tenantId);


    /**
     * getPatientCollectByObjectType 获取患者的收藏记录
     *
     * @param
     * @return
     * @throws
     * @Description:根据登陆用户及对像类型，获取我的收藏列表
     * @author chase
     * @date 2016/4/6
     */
    public List<OdsPatientcollect> getPatientCollectByObjectType(final String userId, final String objectType, final int page, final int limit) {
        HibernateStatelessResultAction<List<OdsPatientcollect>> action = new AbstractHibernateStatelessResultAction<List<OdsPatientcollect>>() {
            @Override
            public void execute(StatelessSession ss) throws Exception {
                Query sqlQuery = ss.createQuery("from OdsPatientcollect where userId=:userId and objectType =:objectType and tenantId=:tenantId");
                sqlQuery.setParameter("userId", userId);
                sqlQuery.setParameter("objectType", objectType);
                String tenantId = UserRoleToken.getCurrentTenantId();
                if (tenantId == null || tenantId.isEmpty()) {
                    tenantId = RpcUserToken.getTenantId();
                }
                sqlQuery.setParameter("tenantId", tenantId);
                sqlQuery.setFirstResult((page - 1) * limit);
                sqlQuery.setMaxResults(limit);
                List<OdsPatientcollect> dbList = sqlQuery.list();
                setResult(dbList);
            }
        };
        HibernateSessionTemplate.instance().execute(action);
        return action.getResult();
    }

    /**
     * @param
     * @return
     * @throws
     * @Description:查询患者收藏
     * @author chase
     * @date 2016/6/30
     */
    public List<OdsPatientcollect> getPatientCollect(final String userId, final int page, final int limit) {
        HibernateStatelessResultAction<List<OdsPatientcollect>> action = new AbstractHibernateStatelessResultAction<List<OdsPatientcollect>>() {
            @Override
            public void execute(StatelessSession ss) throws Exception {
                Query query = ss.createQuery("from OdsPatientcollect where userId=:userId and tenantId=:tenantId ");
                query.setParameter("userId", userId);
                String tenantId = UserRoleToken.getCurrentTenantId();
                if (tenantId == null || tenantId.isEmpty()) {
                    tenantId = RpcUserToken.getTenantId();
                }
                query.setParameter("tenantId", tenantId);
                query.setFirstResult((page - 1) * limit);
                query.setMaxResults(limit );
                List<OdsPatientcollect> dbList = query.list();
                setResult(dbList);
            }
        };
        HibernateSessionTemplate.instance().execute(action);
        return action.getResult();
    }

    private void executeAction(HibernateStatelessAction action) throws ControllerException {
        try {
            HibernateSessionTemplate.instance().executeTrans(action);
        } catch (DAOException e) {
            if (e.getCause() instanceof ControllerException) {
                throw (ControllerException) e.getCause();
            } else {
                throw new ControllerException(e);
            }
        }
    }
}
